package com.loren.demo22.controller;

import com.loren.demo22.entity.TaskDefine;
import com.loren.demo22.execute.JobExecute;
import com.loren.demo22.service.QuartzService;
import lombok.AllArgsConstructor;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@AllArgsConstructor
@RequestMapping("/quartz")
public class QuartzController {

    private final QuartzService quartzService;

    private static final String GROUP_TASK = "dwork_task";

    @GetMapping("/add")
    public String addScheduleJob() throws SchedulerException {
        TaskDefine taskDefine = new TaskDefine();
        JobKey jobKey = JobKey.jobKey(UUID.randomUUID().toString(), GROUP_TASK);
        taskDefine.setJobKey(jobKey);
        taskDefine.setDescription("description-" + jobKey.getName());
        taskDefine.setCronExpression("0 0/1 * * * ?");
        taskDefine.setJobDataMap(null);
        taskDefine.setJobClass(JobExecute.class);
        this.quartzService.addScheduleJob(taskDefine);
        return "success";
    }

    @GetMapping("/delete")
    public String deleteScheduleJob(@RequestParam("job_key") String jobKey) throws SchedulerException {
        this.quartzService.deleteScheduleJob(JobKey.jobKey(jobKey, GROUP_TASK));
        return "success";
    }

    @GetMapping("/pause")
    public String pauseScheduleJob(@RequestParam("job_key") String jobKey) throws SchedulerException {
        this.quartzService.pauseScheduleJob(JobKey.jobKey(jobKey, GROUP_TASK));
        return "success";
    }

    @GetMapping("/resume")
    public String resumeScheduleJob(@RequestParam("job_key") String jobKey) throws SchedulerException {
        this.quartzService.resumeScheduleJob(JobKey.jobKey(jobKey, GROUP_TASK));
        return "success";
    }
}
